﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ifunction
{
    public static partial class ReflectionExtension
    {
        #region Convert Object

        /// <summary>
        /// Converts the objects by <see cref="Type" /> instance.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="value">The value.</param>
        /// <returns>System.Object.</returns>
        public static object ConvertToObjectByType(Type type, string value)
        {
            MethodInfo method = typeof(ReflectionExtension).GetMethod("ConvertToObject");

            MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { type });
            return genericMethod.Invoke(null, new object[] { value });
        }

        /// <summary>
        /// Converts to object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns>``0.</returns>
        /// <exception cref="System.Exception">Failed to convert from string[\ + (string.IsNullOrWhiteSpace(value) ? string.Empty : value) + \] to object[ + typeof(T).FullName + ].</exception>
        public static T ConvertToObject<T>(this string value)
        {
            try
            {
                var converter = TypeDescriptor.GetConverter(typeof(T));
                if (converter != null)
                {
                    //Cast ConvertFromString(string text) : object to (T)
                    return (T)converter.ConvertFromString(value);
                }
                return default(T);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to convert from string[\"" + value.GetStringValue() + "\"] to object[" + typeof(T).FullName + "].", ex);
            }
        }

        #endregion

        #region Invoke methods

        /// <summary>
        /// Invokes the method.
        /// </summary>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="instance">The instance.</param>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="invokeParameters">The invoke parameters.</param>
        /// <param name="genericTypes">The generic types.</param>
        /// <param name="throwException">if set to <c>true</c> [throw exception].</param>
        /// <returns>System.Object.</returns>
        /// <exception cref="System.InvalidCastException">Neither objectType or instance is valid.</exception>
        /// <exception cref="ifunction.Common.OperationFailureException">InvokeMethod</exception>
        public static object InvokeMethod(Type objectType, object instance, string methodName, object[] invokeParameters, Type[] genericTypes = null, bool throwException = false)
        {
            try
            {
                if (objectType == null && instance == null)
                {
                    throw new InvalidCastException("Neither objectType or instance is valid.");
                }
                else
                {
                    if (objectType == null)
                    {
                        objectType = instance.GetType();
                    }

                    MethodInfo methodInfo = objectType.GetMethod(methodName);
                    methodInfo.CheckNullObject("methodName");

                    if (methodInfo.IsStatic)
                    {
                        instance.CheckNullObject("instance");
                    }
                    else
                    {
                        instance = null;
                    }

                    if (methodInfo.IsGenericMethod)
                    {
                        instance.CheckNullObject("genericTypes");
                        methodInfo = methodInfo.MakeGenericMethod(genericTypes);
                    }

                    return methodInfo.Invoke(instance, invokeParameters);
                }
            }
            catch (Exception ex)
            {
                if (throwException)
                {
                    throw new InvalidOperationException(string.Format("InvokeMethod of [{0}] in [{1}]", methodName.GetStringValue(), (objectType == null ? "null" : objectType.FullName), ex));
                }
            }

            return null;
        }

        #endregion
    }
}
